import { Router } from 'vue-router';
import { useUserStoreWidthOut } from '@/store/modules/user';
import { PageEnum } from '@/enums/pageEnum';

// 登录页面路由地址
const LOGIN_PATH = PageEnum.BASE_LOGIN;

// 白名单路由配置
const whitePathList = [LOGIN_PATH];

export function createRouterGuards(router: Router) {
  const userStore = useUserStoreWidthOut();

  router.beforeEach(async (to, from, next) => {
    const Loading = window['$loading'] || null;
    Loading?.start();

    // 登录页 错误页面 过滤
    if (from.path === LOGIN_PATH && to.name === 'errorPage') {
      next(PageEnum.BASE_HOME);
      return;
    }

    // 白名单过滤
    if (whitePathList.includes(to.path as PageEnum)) {
      next();
      return;
    }

    const token = userStore.loginInfo?.secret;

    if (!token) {
      // 未登录
      if (to.meta.ignoreAuth) {
        // 忽略鉴权
        next();
        return;
      }
      // 跳转登录
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }

    // 动态添加可访问路由表
    // routes.forEach((item) => {
    //   router.addRoute(item as unknown as RouteRecordRaw);
    // });
    next();
    Loading?.finish();
  });

  router.afterEach(() => {
    window['$loading']?.finish();
  });

  router.onError((error) => {
    console.log(error, '路由错误');
  });
}
